package com.liufei.class04;

// 力扣链接：https://leetcode.cn/problems/merge-two-sorted-lists/description/
public class Code06_MergeTwoSortedLinkedList {

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null || list2 == null) {
            return list1 == null ? list2 : list1;
        }
        // 谁的第一个值小，谁当头节点，不动了
        ListNode head = list1.val <= list2.val ? list1 : list2;
        ListNode cur1 = head.next;
        ListNode cur2 = head == list1 ? list2 : list1;
        ListNode pre = head;
        // 从l1的下一个节点开始和l2的第一个节点比较
        while (cur1 != null && cur2 != null) {
            if (cur1.val <= cur2.val) {
                pre.next = cur1;
                cur1 = cur1.next;
            } else {
                pre.next = cur2;
                cur2 = cur2.next;
            }
            pre = pre.next;
        }
        pre.next = cur1 == null ? cur2 : cur1;
        return head;
    }
    public static void main(String[] args) {
        ListNode list1 = new ListNode(1, new ListNode(4, new ListNode(6)));
        ListNode list2 = new ListNode(2, new ListNode(5, new ListNode(7)));

        Code06_MergeTwoSortedLinkedList test = new Code06_MergeTwoSortedLinkedList();

        ListNode listNode = test.mergeTwoLists(list1, list2);
        System.out.println(listNode);
    }
}
